using System;
using System.IO;
using Dynastream.Fit;

namespace GarminUploader
{
    public class FitFile
    {
        private static System.DateTime startTime;

        private readonly Decode decoder = new Decode();
        private readonly string filename;

        public FitFile(string filename)
        {
            this.filename = filename;
            startTime = default(System.DateTime);

            // Initialise the decoder and the broadcaster
            MesgBroadcaster broadcaster = new MesgBroadcaster();

            // Connect the Broadcaster to our event (message) source (in this case the Decoder)
            decoder.MesgEvent += broadcaster.OnMesg;       

            // Subscribe to message events of interest by connecting to the Broadcaster
            broadcaster.MesgEvent += new MesgEventHandler(OnMesg);
        }

        public System.DateTime getStartTime()
        {
            // Read the file
            using (FileStream fileStream = System.IO.File.OpenRead(filename))
            {
                try
                {
                    decoder.Read(fileStream);
                }
                catch (Exception exception)
                {
                    throw new FitException("Invalid FIT File.", exception);
                }
            }

            // Throw and exception if a start time isn't found
            if (startTime.Equals(default(System.DateTime)))
            {
                throw new FitException("File is not a valid Activity FIT file.");
            }
            else
            {
                // return the start time loaded by the listening method
                return startTime;
            }
        }

        public byte[] getBytes()
        {
            return System.IO.File.ReadAllBytes(filename);
        }

        public string getName()
        {
            return filename;
        }

        static void OnMesg(object sender, MesgEventArgs e)
        {
            // Check if the message is the session
            if ("Session".Equals(e.mesg.Name))
            {
                // Save the activity id
                int secondsSince89 = Convert.ToInt32(e.mesg.GetFieldValue("StartTime").ToString());
                startTime = new System.DateTime(1989, 12, 31).AddSeconds(secondsSince89);
			}
        }
    }
}